<template>
  <div class="login-container">
    <!-- 背景装饰 -->
    <div class="background-decoration">
      <div class="decoration-circle circle-1"></div>
      <div class="decoration-circle circle-2"></div>
      <div class="decoration-circle circle-3"></div>
    </div>

    <!-- 主要内容 -->
    <div class="login-content">
      <!-- 左侧信息区域 -->
      <div class="login-info">
        <div class="info-content">
          <h1 class="info-title">
            欢迎回到
            <span class="gradient-text">ZenithMind</span>
          </h1>
          <p class="info-subtitle">
            智能学习，成就未来
          </p>
          <div class="info-features">
            <div class="feature-item">
              <el-icon><VideoPlay /></el-icon>
              <span>15个专业学习模块</span>
            </div>
            <div class="feature-item">
              <el-icon><TrendCharts /></el-icon>
              <span>个性化学习路径</span>
            </div>
            <div class="feature-item">
              <el-icon><ChatDotRound /></el-icon>
              <span>AI智能助手</span>
            </div>
            <div class="feature-item">
              <el-icon><Trophy /></el-icon>
              <span>成就激励系统</span>
            </div>
          </div>
          <div class="info-stats">
            <div class="stat-item">
              <div class="stat-number">125K+</div>
              <div class="stat-label">注册用户</div>
            </div>
            <div class="stat-item">
              <div class="stat-number">8.5K+</div>
              <div class="stat-label">优质课程</div>
            </div>
            <div class="stat-item">
              <div class="stat-number">280W+</div>
              <div class="stat-label">学习时长</div>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧登录表单 -->
      <div class="login-form-container">
        <div class="login-form">
          <!-- 头部 -->
          <div class="form-header">
            <h2>登录账户</h2>
            <p>继续您的学习之旅</p>
          </div>

          <!-- 登录方式切换 -->
          <div class="login-tabs">
            <div 
              class="tab-item"
              :class="{ active: loginType === 'password' }"
              @click="loginType = 'password'"
            >
              密码登录
            </div>
            <div 
              class="tab-item"
              :class="{ active: loginType === 'sms' }"
              @click="loginType = 'sms'"
            >
              短信登录
            </div>
          </div>

          <!-- 登录表单 -->
          <el-form
            ref="loginFormRef"
            :model="loginForm"
            :rules="loginRules"
            @submit.prevent="handleLogin"
          >
            <!-- 用户名/手机号 -->
            <el-form-item prop="username">
              <el-input
                v-model="loginForm.username"
                :placeholder="loginType === 'password' ? '请输入用户名/邮箱/手机号' : '请输入手机号'"
                size="large"
                clearable
              >
                <template #prefix>
                  <el-icon><User /></el-icon>
                </template>
              </el-input>
            </el-form-item>

            <!-- 密码登录 -->
            <template v-if="loginType === 'password'">
              <el-form-item prop="password">
                <el-input
                  v-model="loginForm.password"
                  type="password"
                  placeholder="请输入密码"
                  size="large"
                  show-password
                  clearable
                >
                  <template #prefix>
                    <el-icon><Lock /></el-icon>
                  </template>
                </el-input>
              </el-form-item>

              <!-- 图形验证码 -->
              <el-form-item prop="captcha" v-if="showCaptcha">
                <div class="captcha-container">
                  <el-input
                    v-model="loginForm.captcha"
                    placeholder="请输入验证码"
                    size="large"
                    clearable
                  >
                    <template #prefix>
                      <el-icon><Picture /></el-icon>
                    </template>
                  </el-input>
                  <div class="captcha-image" @click="refreshCaptcha">
                    <img :src="captchaImage" alt="验证码" />
                  </div>
                </div>
              </el-form-item>
            </template>

            <!-- 短信登录 -->
            <template v-else>
              <el-form-item prop="smsCode">
                <div class="sms-container">
                  <el-input
                    v-model="loginForm.smsCode"
                    placeholder="请输入短信验证码"
                    size="large"
                    clearable
                  >
                    <template #prefix>
                      <el-icon><Message /></el-icon>
                    </template>
                  </el-input>
                  <el-button
                    :disabled="smsCountdown > 0"
                    @click="sendSmsCode"
                    class="sms-btn"
                    :class="{ 'counting': smsCountdown > 0 }"
                  >
                    {{ smsCountdown > 0 ? `${smsCountdown}s` : '获取验证码' }}
                  </el-button>
                </div>
              </el-form-item>
            </template>

            <!-- 记住我和忘记密码 -->
            <div class="form-options">
              <el-checkbox v-model="loginForm.rememberMe">
                记住我
              </el-checkbox>
              <el-button 
                type="primary" 
                link 
                @click="goForgotPassword"
                v-if="loginType === 'password'"
                class="forgot-pwd-btn"
              >
                忘记密码？
              </el-button>
            </div>

            <!-- 登录按钮 -->
            <el-form-item>
              <el-button
                type="primary"
                size="large"
                :loading="loading"
                @click="handleLogin"
                class="login-btn"
              >
                {{ loading ? '登录中...' : '登录' }}
              </el-button>
            </el-form-item>
          </el-form>

          <!-- 第三方登录 -->
          <div class="social-login">
            <div class="divider">
              <span>或使用以下方式登录</span>
            </div>
            <div class="social-buttons">
              <el-button circle @click="socialLogin('wechat')" class="social-btn wechat">
                <el-icon><ChatDotRound /></el-icon>
              </el-button>
              <el-button circle @click="socialLogin('qq')" class="social-btn qq">
                <el-icon><User /></el-icon>
              </el-button>
              <el-button circle @click="socialLogin('github')" class="social-btn github">
                <el-icon><Link /></el-icon>
              </el-button>
            </div>
          </div>

          <!-- 注册链接 -->
          <div class="register-link">
            还没有账户？
            <el-button type="primary" link @click="goRegister" class="register-btn">
              立即注册
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 返回首页按钮 -->
    <el-button 
      circle 
      @click="goHome"
      class="back-home-btn"
    >
      <el-icon><House /></el-icon>
    </el-button>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { userApi, verificationApi } from '@/api/user'
import { ElMessage } from 'element-plus'
import {
  User, Lock, Picture, Message, VideoPlay, TrendCharts,
  ChatDotRound, Trophy, House, Link
} from '@element-plus/icons-vue'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()

// 响应式数据
const loginFormRef = ref()
const loading = ref(false)
const loginType = ref('password') // 'password' | 'sms'
const showCaptcha = ref(false)
const captchaImage = ref('')
const smsCountdown = ref(0)

const loginForm = reactive({
  username: '',
  password: '',
  verificationCode: '', // 修改为与后端匹配的验证码字段名
  captcha: '',
  smsCode: '',
  rememberMe: false
})

// 表单验证规则
const loginRules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  captcha: [
    { required: true, message: '请输入验证码', trigger: 'blur' }
  ],
  smsCode: [
    { required: true, message: '请输入短信验证码', trigger: 'blur' },
    { pattern: /^\d{6}$/, message: '请输入6位数字验证码', trigger: 'blur' }
  ]
})

// 方法
const handleLogin = async () => {
  try {
    await loginFormRef.value.validate()
    
    loading.value = true
    
    const loginData = {
      username: loginForm.username,
      password: loginForm.password,
      rememberMe: loginForm.rememberMe
    }
    
    if (loginType.value === 'password') {
      // 密码登录
      if (showCaptcha.value && loginForm.captcha) {
        loginData.verificationCode = loginForm.captcha // 使用后端要求的字段名
      }
    } else {
      // 短信登录 - 暂时不支持
      ElMessage.warning('短信登录功能开发中，请使用密码登录')
      loading.value = false
      return
    }
    
    try {
      // 使用简单登录接口进行测试
      let result = await userApi.simpleLogin(loginData)
      if (result.code === 200) {
        // 登录成功，保存用户信息
        const user = result.data
        
        // 在用户store中保存用户信息
        await userStore.setUserInfo(user)
        
        // 获取用户角色和权限（可选，根据需要）
        try {
          // 手动添加一个管理员角色（测试用）
          if (!user.roles) {
            user.roles = ['admin']
          }
        } catch (e) {
          console.warn('获取角色信息失败', e)
        }
        
        ElMessage.success('登录成功')
        
        // 跳转到目标页面或首页
        const redirect = route.query.redirect || '/'
        router.push(redirect)
      } else {
        ElMessage.error(result.msg || '登录失败')
        // 如果需要图形验证码
        if (showCaptcha.value) {
          refreshCaptcha()
        }
      }
    } catch (loginError) {
      console.error('登录请求失败:', loginError)
      ElMessage.error(loginError.message || '登录失败，请检查网络连接')
      
      if (showCaptcha.value) {
        refreshCaptcha()
      }
    }
  } catch (error) {
    console.error('登录参数验证失败:', error)
    
    // 根据错误信息处理
    const errorMessage = error.message || error.response?.data?.msg || '登录失败'
    ElMessage.error(errorMessage)
    
    // 如果是密码错误次数过多，显示验证码
    if (errorMessage.includes('验证码') || errorMessage.includes('captcha')) {
      showCaptcha.value = true
      refreshCaptcha()
    }
  } finally {
    loading.value = false
  }
}

const sendSmsCode = async () => {
  if (!loginForm.username) {
    ElMessage.warning('请先输入用户名')
    return
  }

  try {
    await verificationApi.sendLoginCode({
      username: loginForm.username,
      type: 0 // 0:登录验证码
    })
    
    ElMessage.success('验证码已发送')
    
    // 开始倒计时
    smsCountdown.value = 60
    const timer = setInterval(() => {
      smsCountdown.value--
      if (smsCountdown.value <= 0) {
        clearInterval(timer)
      }
    }, 1000)
    
  } catch (error) {
    console.error('发送验证码失败:', error)
    const errorMessage = error.response?.data?.msg || '发送验证码失败'
    ElMessage.error(errorMessage)
  }
}

const refreshCaptcha = async () => {
  try {
    const response = await verificationApi.getCaptcha()
    captchaImage.value = response.data.image
  } catch (error) {
    console.error('获取验证码失败:', error)
  }
}

const socialLogin = (provider) => {
  ElMessage.info(`${provider} 登录功能开发中...`)
}

const goRegister = () => {
  router.push('/register')
}

const goForgotPassword = () => {
  router.push('/forgot-password')
}

const goHome = () => {
  router.push('/')
}

onMounted(() => {
  // 如果已经登录，直接跳转
  if (userStore.isLoggedIn) {
    const redirect = route.query.redirect || '/dashboard'
    router.push(redirect)
  }
})
</script>

<style lang="scss" scoped>
.login-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  overflow: hidden;
}

.background-decoration {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  pointer-events: none;
  
  .decoration-circle {
    position: absolute;
    border-radius: 50%;
    background: rgba(255, 255, 255, 0.1);
    
    &.circle-1 {
      width: 200px;
      height: 200px;
      top: 10%;
      left: 10%;
      animation: float 6s ease-in-out infinite;
    }
    
    &.circle-2 {
      width: 150px;
      height: 150px;
      top: 60%;
      right: 15%;
      animation: float 8s ease-in-out infinite reverse;
    }
    
    &.circle-3 {
      width: 100px;
      height: 100px;
      bottom: 20%;
      left: 20%;
      animation: float 10s ease-in-out infinite;
    }
  }
}

@keyframes float {
  0%, 100% { transform: translateY(0px); }
  50% { transform: translateY(-20px); }
}

.login-content {
  display: grid;
  grid-template-columns: 1fr 1fr;
  max-width: 1200px;
  width: 100%;
  margin: 0 auto;
  padding: 40px;
  gap: 60px;
  align-items: center;
}

.login-info {
  color: white;
  
  .info-title {
    font-size: 3rem;
    font-weight: 700;
    line-height: 1.2;
    margin-bottom: 20px;
    
    .gradient-text {
      background: linear-gradient(45deg, #fff, #f0f8ff);
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
      background-clip: text;
    }
  }
  
  .info-subtitle {
    font-size: 1.25rem;
    margin-bottom: 40px;
    opacity: 0.9;
  }
  
  .info-features {
    margin-bottom: 40px;
    
    .feature-item {
      display: flex;
      align-items: center;
      gap: 12px;
      margin-bottom: 16px;
      font-size: 1rem;
      opacity: 0.8;
    }
  }
  
  .info-stats {
    display: flex;
    gap: 40px;
    
    .stat-item {
      text-align: center;
      
      .stat-number {
        font-size: 2rem;
        font-weight: 700;
        margin-bottom: 8px;
      }
      
      .stat-label {
        font-size: 0.9rem;
        opacity: 0.8;
      }
    }
  }
}

.login-form-container {
  .login-form {
    background: white;
    border-radius: 20px;
    padding: 40px;
    box-shadow: 0 20px 60px rgba(0, 0, 0, 0.1);
    
    :deep(.el-input__wrapper) {
      padding: 0 15px;
      height: 48px;
      border-radius: 12px;
      box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
      transition: all 0.3s;
      
      &:hover, &:focus-within {
        box-shadow: 0 2px 12px rgba(102, 126, 234, 0.2);
      }
      
      .el-input__prefix {
        padding-right: 10px;
        color: #667eea;
      }
    }
    
    .form-header {
      text-align: center;
      margin-bottom: 30px;
      
      h2 {
        font-size: 1.8rem;
        font-weight: 600;
        color: var(--el-text-color-primary);
        margin-bottom: 8px;
      }
      
      p {
        color: var(--el-text-color-secondary);
      }
    }
    
    .login-tabs {
      display: flex;
      background: var(--el-bg-color-page);
      border-radius: 12px;
      padding: 4px;
      margin-bottom: 30px;
      
      .tab-item {
        flex: 1;
        text-align: center;
        padding: 12px;
        border-radius: 8px;
        cursor: pointer;
        transition: all 0.3s ease;
        
        &.active {
          background: white;
          color: var(--el-color-primary);
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        }
      }
    }
    
    .form-options {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;
    }
    
    .login-btn {
      width: 100%;
      height: 48px;
      font-size: 1.1rem;
      border-radius: 12px;
    }
    
    .social-login {
      margin-top: 30px;
      
      .divider {
        text-align: center;
        position: relative;
        margin-bottom: 20px;
        
        &::before {
          content: '';
          position: absolute;
          top: 50%;
          left: 0;
          right: 0;
          height: 1px;
          background: var(--el-border-color);
        }
        
        span {
          background: white;
          padding: 0 20px;
          color: var(--el-text-color-secondary);
          font-size: 0.9rem;
        }
      }
      
      .social-buttons {
        display: flex;
        justify-content: center;
        gap: 16px;
        
        .social-btn {
          width: 48px;
          height: 48px;
          border-radius: 50%;
          
          &.wechat {
            background: #07c160;
            border-color: #07c160;
            color: white;
          }
          
          &.qq {
            background: #12b7f5;
            border-color: #12b7f5;
            color: white;
          }
          
          &.github {
            background: #333;
            border-color: #333;
            color: white;
          }
        }
      }
    }
    
    .register-link {
      text-align: center;
      margin-top: 20px;
      color: var(--el-text-color-secondary);
    }
  }
}

.back-home-btn {
  position: fixed;
  top: 30px;
  left: 30px;
  width: 48px;
  height: 48px;
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  color: white;
  backdrop-filter: blur(10px);
  
  &:hover {
    background: rgba(255, 255, 255, 0.2);
  }
}

// 响应式设计
@media (max-width: 1024px) {
  .login-content {
    grid-template-columns: 1fr;
    gap: 40px;
    padding: 20px;
  }
  
  .login-info {
    text-align: center;
    
    .info-title {
      font-size: 2.5rem;
    }
    
    .info-stats {
      justify-content: center;
    }
  }
}

@media (max-width: 768px) {
  .login-form-container .login-form {
    padding: 30px 20px;
  }
  
  .login-info .info-title {
    font-size: 2rem;
  }
  
  .back-home-btn {
    top: 20px;
    left: 20px;
  }
}

.captcha-container,
.sms-container {
  display: flex;
  gap: 12px;
}

.sms-container {
  .el-input {
    flex: 1;
  }
  
  .sms-btn {
    white-space: nowrap;
    min-width: 120px;
    height: 48px;
    border-radius: 12px;
    font-size: 14px;
    font-weight: 500;
    transition: all 0.3s;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border: none;
    color: white;
    
    &:hover:not(:disabled) {
      transform: translateY(-2px);
      box-shadow: 0 6px 16px rgba(102, 126, 234, 0.3);
    }
    
    &:active:not(:disabled) {
      transform: translateY(0);
    }
    
    &.counting {
      background: #f5f7fa;
      color: #909399;
      border: 1px solid #dcdfe6;
    }
    
    &:disabled {
      background: #f5f7fa;
      color: #909399;
      border: 1px solid #dcdfe6;
      cursor: not-allowed;
    }
  }
}

.form-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  
  .forgot-pwd-btn {
    font-size: 14px;
    font-weight: 500;
    color: #667eea;
    padding: 0;
    transition: all 0.3s;
    
    &:hover {
      color: #4a5ce1;
      text-decoration: underline;
      transform: translateY(-1px);
    }
  }
}

.register-link {
  text-align: center;
  margin-top: 20px;
  color: var(--el-text-color-secondary);
  
  .register-btn {
    font-size: 15px;
    font-weight: 600;
    color: #667eea;
    padding: 0 4px;
    transition: all 0.3s;
    
    &:hover {
      color: #4a5ce1;
      text-decoration: underline;
      transform: translateY(-1px);
    }
  }
}

.captcha-container {
  .el-input {
    flex: 1;
  }
  
  .captcha-image {
    width: 120px;
    height: 48px;
    cursor: pointer;
    border-radius: 12px;
    overflow: hidden;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
    transition: all 0.3s;
    
    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
    }
    
    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
  }
}
</style>
